<template>
  <header class="pages-header">
    <div class="pages-header-content">
      <div
        class=""
        :class="{
          'pages-header-back': true,
          'touch': backTouch
        }"
        v-tap.status.stop="_back"
        v-html="back.template"
      ></div>
      <div class="pages-header-title"><p><slot /></p></div>
      <ul class="pages-header-menu">
        <li v-for="(btn, key) in rightButton" :key="key"
          v-html="btn.template"
          v-tap.stop="btn.tap"
        >
        </li>
      </ul>
    </div>
  </header>
</template>

<script>
  export default {
    name: "pages-header",
    data() {
      return {
        backTouch: false
      }
    },
    props: {
      back: {
        type: [Object, Boolean],
        default() {
          return {
            template: '返回',
            tap: null
          }
        }
      },
      rightBtn: {
        type: Array,
        default() {
          return []
        }
      }
    },
    methods: {
      _back(e) {
        if(this.back === false)
          return
        if(e.type === 'tapstart')
          this.backTouch = true
        else
          this.backTouch = false

        if(e.type === 'tap')
          if(this.back.tap && typeof this.back.tap === 'function')
            this.back.tap(() => {
              this.$router.back()
            })
          else
            this.$router.back()
      },
      computeHeight() {
        this.$nextTick(() => {
          setTimeout(() => {
            const el = window.getComputedStyle(this.$el.querySelector('.pages-header-content'))
            const top = parseInt(el.paddingTop)
            const height = parseInt(el.height)
            this.$parent.top = height + top
          },0)
        })
        this.$parent.top = true
      },
      resize() {
        this.computeHeight()
      }
    },
    computed: {
      rightButton() {
        const btn = []

        for(let i = 0; i < 2; i++)
          if(this.rightBtn[i])
            btn.push(this.rightBtn[i])

        return btn
      }
    },
    mounted(){
      window.addEventListener('resize', this.resize, false)
      this.computeHeight()
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resize)
    }
  }
</script>
